﻿var logo = ""; var conamevlue = "";
$(window).resize(function () {

    $("#table_list_1").setGridWidth($(window).width());
    $("#table_list_1").setGridHeight($(window).height() - 248);
});
function uuid() {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "-";

    var uuid = s.join("");
    return uuid;
}
function add() {
    var AZ = ["devicenumber", "devicename", "type", "high", "width", "status", "maxprogramnum", "maxPSDnum", "maxregionnum",
        "address", "Longitude", "Latitude", "company_id"];
    //字段 
    var sum = 1;
    if ($("#deviceid").val() == "") {

        swal("OMG!", "请输入设备编号", "error");
        return;
    }
    if ($("#deviceid").val().length < 12) {

        swal("OMG!", "输入设备编号不能小于12位", "error");
        return;
    }
    if ($("#typecz").val() == "1") {

        if ($("#sum").val() == "" || $("#sum").val() == "0") {

            swal("OMG!", "请输入设备数量", "error");
            return;
        } else {
            sum = $("#deviceid").val().substring(9);
            sum = parseInt(sum) + parseInt($("#sum").val());





            if (parseInt(sum) > 1000) {

                swal("OMG!", "输入的设备号超过了1000数量", "error");
                return;
            }
        }

        sum = $("#sum").val();

    }
    if ($("#devicename").val().length == 0) {
        // swal("OMG!", "名称不能为空", "error");
        // return;
        $("#devicename").val($("#deviceid").val());
    }

    if ($("#high").val() == "") {

        swal("OMG!", "请输入屏高", "error");
        return;
    }
    if ($("#width").val() == "") {

        swal("OMG!", "请输入屏宽", "error");
        return;
    }
    var val = [$("#deviceid").val(), $("#devicename").val(), $("#type").val(), $("#high").val() == "" ? 0 : $("#high").val(), $("#width").val() == "" ? 0 : $("#width").val(), 1,
    $("#maxprogramnum").val() == "" ? "0" : $("#maxprogramnum").val(), $("#maxPSDnum").val() == "" ? "0" : $("#maxPSDnum").val(), $("#maxregionnum").val() == "" ? "0" : $("#maxregionnum").val(), $("#address").val(), $("#Longitude").val() == "" ? 0 : $("#Longitude").val(), $("#Latitude").val() == "" ? 0 : $("#Latitude").val(), $("#company_id").val()];

    // devicenumber设备号，devicename设备名称，type设备类型 high高度 width 宽度companyid卡组id address 地址maxprogramnum 节目容量 maxPSDnum 素材容量maxregionnum区域容量 longitude 经度，latitude纬度 remark 说明，devicesum批量多少


    var dataval = {
        sessionid: sessionStorage.getItem("sid"), "devicenumber": $("#deviceid").val(), "devicename": $("#devicename").val(),
        "type": $("#type").val(), "companyid": sessionStorage.getItem("coid"), "high": $("#high").val(), "width": $("#width").val(),
        "address": $("#address").val(), "maxprogramnum": $("#maxregionnum").val(),
        "maxPSDnum": $("#maxPSDnum").val(), "maxregionnum": $("#maxregionnum").val(),
        "longitude": $("#Longitude").val(),
        "latitude": $("#Latitude").val(),
        "devicesum": sum
    };





    if ($("#myModalLabel").text() == "新增" || conamevlue != $("#deviceid").val()) {
        // alert($("#company_id").val());
        var findval = domain.fieldthis(AZ, val, "deviceinfo");


        $.ajax({
            url: domain.testUrl + "/Threeinjection/DeviceManagement/queryDeviceInfoDeviceName",
            type: "post",
            dataType: "json",
            data: { "sessionid": sessionStorage.getItem("sid"), "devicenumber": $("#deviceid").val() },
            success: function (data) {

                console.log(data);

                if (data.code == "200") {
                    //var json=
                    // {"tableName":"userinfo", "fielded":""，” valueid”:”修改条件”,”fieldnameA”:”需要修改的字段”，”stringvalueA”:”修改值” }
                    $.fn.jqLoading({ height: 100, width: 240, text: "正在保存中，请耐心等待...." });

                    $.ajax({
                        type: "post",
                        //url:domain.testUrl+"/Threeinjection/global/insert",
                        url: domain.testUrl + "/Threeinjection/DeviceManagement/insertDevice",
                        data: dataval,
                        //  timeout: 8000,//超时设置
                        success: function (response) {
                            // console.log(response);
                            response = JSON.parse(response);
                            //swal("success!", "保存成功", "success");
                            $.fn.jqLoading("destroy");
                            if (response.code == "200") {
                                $(".close").click();
                                pageval = 1;
                                cxlist();
                                swal("success!", "保存成功", "success");
                               
                            } else {

                                swal("OMG!", "保存失败！", "error");
                            }
                        }
                        ,
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            $.fn.jqLoading("destroy");
                            swal("OMG!", "保存失败", "error");
                        },
                        complete: function (XMLHttpRequest, status) {

                            if (status == 'timeout') {
                                // swal("OMG!", "保存失败", "error");

                            }
                        }
                    });
                } else {
                    swal("OMG!", "设备编号已存在", "error");

                }
            }
        });
    } else {
        AZ = ["devicename", "type", "high", "width", "status", "maxprogramnum", "maxPSDnum", "maxregionnum",
            "address", "Longitude", "Latitude", "company_id"];

        val = [$("#devicename").val(), $("#type").val(), $("#high").val() == "" ? 0 : $("#high").val(), $("#width").val() == "" ? 0 : $("#width").val(), 1,
        $("#maxprogramnum").val() == "" ? "0" : $("#maxprogramnum").val(), $("#maxPSDnum").val() == "" ? "0" : $("#maxPSDnum").val(), $("#maxregionnum").val() == "" ? "0" : $("#maxregionnum").val(), $("#address").val(), $("#Longitude").val() == "" ? 0 : $("#Longitude").val(), $("#Latitude").val() == "" ? 0 : $("#Latitude").val(), $("#company_id").val()];
        var findval = domain.fieldupdatethis(AZ, val, "devicenumber", "'" + $("#co_idadd").val() + "'", "deviceinfo");
        domain.ajaxUrl({
            method: 'POST',
            url: domain.testUrl + "/Threeinjection/global/update",
            data: findval,
            success: function (response) {
                //console.log(response);
                response = JSON.parse(response);
                if (response.code == "200") {
                    pageval = 1;
                    cxlist(); conameval = "";
                    $(".close").click();
                    swal("success!", "修改成功", "success");
                }
            }
        });
    }
}

///Threeinjection/DeviceManagement/queryCompanyandDevice
var idval = ""; var type = ""; //设备号
var data = {};
$(function () {
    if (sessionStorage.getItem("isgroup") == "0") {
        $("#addt").hide(); $(".btn-primary").eq(1).hide();
    } else {
        $("#addt").show();

        $(".wx").show();
    }
    $("#Taxi_Five").change(function () {

        //alert(123);
        //wx
        $("#wx td").hide();

        for (var i = 0; i < $(this).val(); i++) {


            $("#wx td").eq(i).show();

        }

    });

    //五星好评
    $("#addpf").click(function () {
        idval = "";
        var isChecked = $('#wxis').is(":checked");
        isChecked = isChecked == true ? "1" : "0";
        var color_five_buff = new Array();

        $("#wx td").each(function () {

            var display = $(this).css('display');
            console.log(display);
            if (display != 'none') {
                color_five_buff.push($(this).find("select").get(0).selectedIndex);
                // console.log($(this).find("select").get(0).selectedIndex);
            }
        });

        var setTaxiDeivceF4Command =

        {
            "RW_Flag": 0,
            "Taxi_Ver": 0,
            "Save_Flag": 0,
            "Write_Flag": 0,
            "Taxi_Empty_Flag": 0,
            "Taxi_Empty_State": 0,
            "Taxi_Default_State": 0,
            "Taxi_Five": isChecked,
            "five_buff_cfg": $("#Taxi_Five").val(),
            "color_five_buff": color_five_buff.join(','),
            "Extern_Lens": 0,
        };


        // console.log(setTaxiDeivceF4Command);
        //  setTaxiDeivceF4Command: {
        //   RW_Flag: int型,
        //   Taxi_Ver: int型,
        //  Save_Flag: int型,
        //  Write_Flag: int型,
        //  Taxi_Empty_Flag": int型,
        // Taxi_Empty_State: int型,
        // Taxi_Default_State: int型,
        // Taxi_Five: int型,
        // five_buff_cfg: int型,
        // color_five_buff: 选择多种颜色以逗号分割,
        //Extern_Lens: int型
        //}
        var ids = $("#table_list_1").jqGrid("getGridParam", "selarrrow");

        //遍历访问这个集合
        $(ids).each(function (index, id) {
            //由id获得对应数据行
            var row = $("#table_list_1").jqGrid('getRowData', id);
            var type1 = row.type;
            if (type1 == "全彩") {

                idval += row.devicenumber;
            } else {
                idval += row.devicenumber + ",";

            }

            //

            //console.log("row.ID:"+row.programid);
            if (type1 == "单色") {

                type = 0;
            }
            if (type1 == "双色") {

                type = 1;
            }

            if (type1 == "全彩") {

                type = 2;
            }




            if (type1 == "安卓") {

                type = 3;
            }
        });

        if (idval == "") {

            swal("OMG!", "请选择设备", "error");
            return;
        }
        if (idval.indexOf(',') != -1) {
            idval = idval.substring(0, idval.length - 1);
        }
        $.fn.jqLoading({ height: 100, width: 240, text: "保存中，请耐心等待...." });
        $.ajax({
            type: 'POST',
            url: domain.testUrl + "/Threeinjection/DeviceManagement/setTaxiDeivce",
            data: { "setTaxiDeivceF4Command": JSON.stringify(setTaxiDeivceF4Command), "devicenumber": idval, "deviceType": type, "companyId": sessionStorage.getItem("coid"), cmd: "244", sessionid: sessionStorage.getItem("sid") },
            //timeout: 5000,//超时设置
            success: function (response) {
                response = JSON.parse(response);
                if (response.code == "200") {
                    $.fn.jqLoading("destroy");
                    swal("success!", "保存成功", "success");
                } else {
                    $.fn.jqLoading("destroy");
                    swal("OMG!", "保存失败", "error");
                }
            }, error: function (data) {
                $.fn.jqLoading("destroy");
                swal("OMG!", "保存失败", "error");
            }
        });
    });


    var materialinfo = new Array();

    $("#del").click(function () {
        materialinfo = new Array();
        id = ""; idva = "";
        var ids = $("#table_list_1").jqGrid("getGridParam", "selarrrow");

        //遍历访问这个集合
        $(ids).each(function (index, id) {
            //由id获得对应数据行
            var row = $("#table_list_1").jqGrid('getRowData', id);
            idval += row.devicenumber + ",";

            var type1 = row.type;
            //console.log("row.ID:"+row.programid);
            if (type1 == "单色") {

                type = 0;
            }
            if (type1 == "双色") {

                type = 1;
            }

            if (type1 == "全彩") {

                type = 2;
            }




            if (type1 == "安卓") {

                type = 3;
            }

            materialinfo.push({
                "devicenumber": row.devicenumber,
                "devicetype": type

            });

        });

        if (idval == "") {

            swal("OMG!", "请选择设备", "error");
            return;
        }

        data["devicelist"] = materialinfo;
        // {
        //   "devicelist": [{
        //    "devicenumber": "1811237LK001",
        //  "devicetype": "0"
        //   }]
        //}
        console.log(JSON.stringify(data));
        var msg = "确定删除这个设备吗？"; 
      if (confirm(msg)==true){         
        $.ajax({
            type: 'POST',
            url: domain.testUrl + "/Threeinjection/DeviceManagement/deleteDeviceInfo",
            data: { "devicelist": JSON.stringify(materialinfo), "companyid": sessionStorage.getItem("coid"), sessionid: sessionStorage.getItem("sid") },
            // timeout: 5000,//超时设置
            success: function (response) {
                response = JSON.parse(response);
                if (response.code == "200") {


                    pageval = 1;
                    cxlist();

                    swal("success!", "删除成功", "success");

                }

            }, error: function (data) {


                swal("OMG!", "删除失败", "error");

            },
            complete: function (XMLHttpRequest, status) {

                if (status == 'timeout') {
                    // swal("OMG!", "删除失败", "error");

                }
            }
        });
          return true; 
     }else{  
         return false;  
     
     }  
     
    });



    $("#addt").click(function (z) {
        $("#plcz").show();
        $("#myModal").find("span").empty(); $("#myModal").find("input").val("");
        $("#myModalLabel").text("新增");
        $('#type').removeAttr("disabled");
        $("#deviceid").attr("disabled", false);

        $("#type").val(sessionStorage.getItem("type"));
        $("#high").val(sessionStorage.getItem("high"));
        $("#width").val(sessionStorage.getItem("width"));
    });
    $("button").eq(0).click(function () {
        coidval = "";
        sizeval = 20;
        pageval = 1;
        $(".ui-pg-selbox").val(20);
        $("#table_list_1").setGridParam({rowNum:20});
        cxlist();
    });
    cxlist();
//$("#citySel").click(function () {
  //      var cityObj = $("#citySel");
    //    var cityOffset = $("#citySel").offset();
        //   alert(cityOffset.left-350);
      //  $("#menuContentmk").show();
        //   $("#menuContent").css({left:cityOffset.left + "px", top:cityOffset.top + cityObj.outerHeight() + "px"}).slideDown("fast");
        //$("body").bind("mousedown", onBodyDown);
    //});
    $("#company_name").click(function () {
        //  $("#co_id").val();
        //$("#co_id").val();
        $("#treeDemocompanytow").width(410);
        var cityObj = $("#company_name");
        var cityOffset = $("#company_name").offset();
        $("#menuContenttow").show();
        $("body").bind("mousedown", onBodyDowntow);
    });

    $("#logoimg").click(function () {
        $("#logo").click();
    });
    $('#logo').change(function () {
        handleFileSelect(this);

    });
    $("#add").click(function () {
        $("#myModal").find("span").empty();

        //if($("#co_name").val().length>0 && $("#co_name").val().length<6){
        //   $("#myModal").find("span").eq(0).text("长度只能在6-20个字符之间");
        //  $("#user_name").focus();  
        //  return;
        //}
        //alert($("#myModal").find(".form-group").eq(2).css('display'));
        // alert($("#myModal").find(".form-group").eq(2).is(':hidden'));
        add();

        //if($("#company_name").val().length==0){

        // $("#myModal").find("span").eq(1).text("单位名称不能为空");
        //return;
        //}



        // if(conamevlue!=$("#devicename").val()){
        //  domain.ajaxUrl({
        //  method: 'POST',
        //  url: domain.testUrl+"/Threeinjection/basicmManagementpage/queryCoNameByCoName",
        //  data: {"coname":$("#co_name").val()},
        //   success: function (response) {
        //     response=JSON.parse(response);
        //   if(response.code=="201"){

        //   $("#myModal").find("span").eq(0).text("名称已经存在");
        // $("#user_name").focus();
        //  return;
        // }else{
        // add();

        // }

        // }
        // });

        // }else{


        //}
    });
});

// if($("#citySel").val().length==0){

// $("#myModal").find("span").eq(3).text("请选择功能模块");
//  return;
// }


if (window.File && window.FileReader && window.FileList && window.Blob) {
    //Blob是计算机界通用术语之一，全称写作：BLOB (binary large object)，表示二进制大对象。
    //全部支持
    window.handleFileSelect = function (target) {
        logo = "";
        var logoimg = document.getElementById("logoimg");
        logoimg.src = "./static/img/upload.jpg";

        var files = target.files, f = files[0];
        if (!/image\/\w+/.test(f.type)) {
            swal("", "请确保文件为图像类型", "error");
            return false;
        }

        var zt = fileChangelog(document.getElementById("logo"));

        if (zt) {

            var reader = new FileReader();
            reader.onload = (function (theFile) {
                return function (e) {

                    var logoimg = document.getElementById("logoimg");

                    logoimg.src = e.target.result;
                };
            })(f);
            reader.readAsDataURL(f);
            var formData = new FormData();
            formData.append('file', $('#logo')[0].files[0]);
            $.ajax({
                url: domain.testUrl + "/Threeinjection/basicmManagementpage/logoFileUpload",
                type: 'POST',
                cache: false,
                data: formData,
                processData: false,
                contentType: false
            }).done(function (res) {
                logo = res;
                //res=logo;


            }).fail(function (res) {



            });



        }
    }
    //	 document.getElementById('logo').addEventListener('change', handleFileSelect, false);

}

var isIE = /msie/i.test(navigator.userAgent) && !window.opera;
function fileChangelog(target) {
    var fileSize = 0;
    if (isIE && !target.files) {
        var filePath = target.value;
        var fileSystem = new ActiveXObject("Scripting.FileSystemObject");
        var file = fileSystem.GetFile(filePath);
        fileSize = file.Size;

    } else {
        fileSize = target.files[0].size;

    }
    var size = fileSize / 1024;
    // alert(size);
    if (size > 5120) {
        // $("#logoimgtext").text("图片不能大于2M,请重新选择！");
        swal("", "图片不能大于5M,请重新选择！", "error");
        return false;
    }
    return true;
}


$(document).ready(function () {

    $("#ok").click(function () {
        var type = ""; var sbhao = "";
        var type2 = ""; var sbhao2 = ""; var cooid = "";
        var ids = $("#table_list_1").jqGrid("getGridParam", "selarrrow");

        //遍历访问这个集合
        $(ids).each(function (index, id) {
            //由id获得对应数据行
            var row = $("#table_list_1").jqGrid('getRowData', id);
            // console.log(row);
            cooid = row.co_id;
            if (row.type == "单色") {

                sbhao += row.devicenumber + ","; type = 0;

            }
            if (row.type == "双色") {

                sbhao += row.devicenumber + ","; type = 1;
            }
            if (row.type == "全彩") {

                sbhao2 += row.devicenumber+ ",";
                type2 = 2;
            }
            if (row.type == "安卓") {

                sbhao2 += row.devicenumber+ ",";
                type2 = 3;
            }
            //console.log("row.ID:"+row.programid);
        });
        sbhao = sbhao.substring(0, sbhao.length - 1);
        //  sbhao2=sbhao2.substring(0,sbhao2.length-1);  
        if (sbhao == "" && sbhao2 == "") {
            swal("", "请选择设备号", "error");

            return;
        }

        if (sbhao.length > 0) {
            $.fn.jqLoading({ height: 100, width: 240, text: "下发指令中，请耐心等待...." });
            $.ajax({
                url: domain.testUrl + "/Threeinjection/DeviceManagement/deviceCommand",
                type: "post",
                dataType: "json",
                timeout: 1000000,//超时设置
                data: { "sessionid": sessionStorage.getItem("sid"), "companyId": cooid, "devicenumber": sbhao, "cmd": $("#zl").val(), "deviceType": type },
                success: function (data) {


                    if (data.code == "200") {
                        $.fn.jqLoading("destroy");
                        swal("success!", "操作成功", "success");

                    } else {
                        $.fn.jqLoading("destroy");
                        swal("", "操作失败", "error");
                    }
                }, error: function (data) {

                    $.fn.jqLoading("destroy");
                    swal("OMG!", "操作失败", "error");

                },
                complete: function (XMLHttpRequest, status) {

                    if (status == 'timeout') {
                        $.fn.jqLoading("destroy");
                        swal("OMG!", "操作失败", "error");

                    }
                }
            });
        } else {
            $.fn.jqLoading({ height: 100, width: 240, text: "下发指令中，请耐心等待...." });
            $.ajax({
                url: domain.testUrl + "/Threeinjection/DeviceManagement/deviceCommand",
                type: "post",
                dataType: "json",
                timeout: 5000000,//超时设置
                data: { "sessionid": sessionStorage.getItem("sid"), "companyId": cooid, "devicenumber": sbhao2, "cmd": $("#zl").val(), "deviceType": type2 },
                success: function (data) {


                    if (data.code == "200") {
                        $.fn.jqLoading("destroy");
                        swal("success!", "操作成功", "success");



                    } else {
                        $.fn.jqLoading("destroy");
                        swal("", "操作失败", "error");
                    }
                }, error: function (data) {

                    $.fn.jqLoading("destroy");
                    swal("OMG!", "操作失败", "error");

                }, complete: function (XMLHttpRequest, status) {

                    if (status == 'timeout') {
                        $.fn.jqLoading("destroy");
                        swal("OMG!", "操作失败", "error");

                    }
                }
            });

        }


    });


    $.jgrid.defaults.styleUI = "Bootstrap";
    $("#table_list_1").jqGrid({
        data: [],
        datatype: "local",
        height: "100%",
        shrinkToFit: true,
        autoScroll: true,
        rowNum: 20,
        rowList: [10, 20, 30, 60, 90, 100, 200, 500],
        //colNames: ["编号", "名称", "手机号码"],
        colModel: [{
            name: 'devicenumber', index: 'devicenumber', align: "center", width: 30, label: "编号", align: 'center',


        },
        {
            name: 'co_id', index: 'co_id', align: "center", width: 25, label: "编号", align: 'center', hidden: true,


        },


        {
            name: 'devicename', index: 'devicename', align: "center", width: 26, label: "名称", align: 'center',


        },

        {
            name: 'co_name', index: 'co_name', align: "center", width: 25, label: "所属单位", align: 'center',


        },



        {
            name: 'type', index: 'type', align: "center", width: 18, label: "类型", align: 'center',
            formatter: function (value, options, row) {

                if (value == "0") {


                    return "单色";

                }

                if (value == "1") {

                    return "双色";
                }

                if (value == "2") {

                    return "全彩";
                }

                if (value == "3") {

                    return "安卓";
                }

            }
        },
        {
            name: 'width', index: 'width', align: "center", width: 18, label: "屏宽", align: 'center',


        },
        {
            name: 'high', index: 'high', align: "center", width: 18, label: "屏高", align: 'center',
        },
        
        {
            hidden: true, name: 'maxprogramnum', index: 'maxprogramnum', align: "center", width: 30, label: "节目容量", align: 'center',


        },

        // {
        //     name: 'coName', index: 'coName',align:"center", width: 25, label:"功能模块", align: 'center',
        // }, 

        {
            hidden: true, name: 'maxPSDnum', index: 'maxPSDnum', align: "center", width: 30, label: "素材容量", align: 'center',


        },
        {
            hidden: true, name: 'maxregionnum', File_server_name: 'maxregionnum', align: "center", width: 30, label: "区域容量", align: 'center',


        },

        {
            hidden: true, name: 'address', index: 'address', align: "center", width: 30, label: "安装位置", align: 'center',


        },
        {
            hidden: true, name: 'Longitude', index: 'Longitude', align: "center", width: 30, label: "经度", align: 'center',


        },
        {
            hidden: true, name: 'Latitude', index: 'Latitude', align: "center", width: 30, label: "纬度", align: 'center',


        },
     
        {
            name: 'isonline', index: 'isonline', align: "center", width: 16, label: "状态", align: 'center',
            formatter: function (value, options, row) {
                if (value == "1") {
                    value = "<img src=static/img/zx.png class=img-rounded style=width:36px;>";

                } else {
                    value = "<img src=static/img/lx.png class=img-rounded style=width:32px;>";


                }
                return value;

            }

        },
        {
            name: 'card_phone', index: 'card_phone', align: "center", width: 30, label: "SSID", align: 'center',
            formatter: function (value, options, row) {
                if (typeof (value) != "undefined") {
               if(value=="111111"){

                return "";
               }
               return value;
            }else{

                return "";
            }
            
        }
        
        },
        {
            name: 'lastonlinetime', index: 'lastonlinetime', align: "center", width: 33, label: "最后在线时间", align: 'center',
            formatter: function (value, options, row) {

                if (typeof (value) != "undefined") {
                    try {
                        var date = new Date(value)

                        return date.Format("yyyy-MM-dd hh:mm:ss");
                    } catch (ex) {

                        console.log(ex);
                    }
                }
                return "";
            }


        },

        {
            name: '', index: '', width: 16, align: "center", label: "节目状态", align: 'center',
            formatter: function (value, options, row) {
               
                var html = "<a onclick=state('"+row.devicenumber+"');>查看</a>";
                return html;
         }
        },

        {
            name: '', index: '', width: 25, align: "center", label: "操作", align: 'center',
            formatter: function (value, options, row) {
                
               
                var html = "<button type='button'  class='btn btn-primary' onclick=modify('" + options.rowId + "');>修改</button>";

                return html;
            }

        },


        ],
        pager: "#pager_list_1",
        viewrecords: true,
        caption: "设备列表",
        hidegrid: false,
        multiselect: true,
        ondblClickRow: function (row) {


            $("#update").click();
            modify(row);
            // $('#myModal').modal('show')

        },
        onPaging: function (pageBtn) {
            console.log(":" + pageBtn);
            //	    	var re_records = $jqgrid.getGridParam('records');//获取返回的记录数
            var re_page = $("#table_list_1").getGridParam('page');//获取返回的当前页
            var re_rowNum = $("#table_list_1").getGridParam('rowNum');//获取每页数
            var re_total = $("#table_list_1").getGridParam('lastpage');//获取总页数
            //alert(re_total);

            if (pageBtn === "next") {
                // initJqgrid(re_page+1,re_rowNum);
                // if()
                pageval = pageval + 1;
                cxlist();
            }
            if (pageBtn === "prev") {

                pageval = pageval - 1; cxlist();
            }

            if (pageBtn == "last") {

                pageval = re_total;

                cxlist();

            }
            if (pageBtn == "first") {

                pageval = 1;

                cxlist();

            }

            if (pageBtn == "records") {

                sizeval = $(".ui-pg-selbox").val();
                pageval = 1;
                cxlist();
            }
        },

    });
});


window.sizeval = 20;
window.pageval = 1; window.coidval = "";
window.conameval = $("#usnameval").val();
var json = "";
window.listsx = function () {
    if (sessionStorage.getItem("isgroup") == "0") {
        $("#addt").hide(); $(".btn-primary").eq(1).hide();
    } else {
        $("#addt").show();

        $(".wx").show();
    }
    cxlist();
};
window.cxlist = function () {
    //http://192.168.1.134:8080/Threeinjection/DeviceManagement/queryDevicePaging
    $.ajax({
        type: "POST",
        //url: "上传图片接口",
        url: domain.testUrl + "/Threeinjection/DeviceManagement/queryDevicePaging",
        data: { size: sizeval, page: pageval, type: $("#typecx").val(), "coid": sessionStorage.getItem("coid"), devicenumber: $("#usnameval").val(), sessionid: sessionStorage.getItem("sid") },
        //视情况将base64的前面字符串data:image/png;base64,删除
        //  async:false,
        // datatype:"JSON",
        success: function (response) {
            //console.log(response);
            json = response;
            var data = JSON.parse(response);
            var reader = {
                root: function (obj) { return data.rows; },
                page: function (obj) { return pageval; },
                total: function (obj) { return data.taotal; },
                records: function (obj) {

                    return data.records;
                },
            };
            $("#table_list_1").setGridParam({ data: data.rows, localReader: reader }).trigger('reloadGrid');

            var re_records = $("#table_list_1").getGridParam('records');

            if (re_records == 0 || re_records == null) {
                if ($(".norecords").html() == null) {
                    $("#usnameval").val("");
                    $("#table_list_1").parent().append("<div class=\"norecords\">没有符合数据</div>");
                }
                $(".norecords").show();
            } else {

                $(".norecords").hide();
            }

            ///alert(json);


            $("#table_list_1").setGridHeight($(window).height() - 248);
            //$("#table_list_1").setGridWidth($(".col-md-12").width()-200);

            $("#table_list_1").setGridWidth($(window).width() - 3);
            //  $("#table_list_1").closest(".ui-jqgrid-bdiv").css({ 'overflow-x' : 'auto' });
           
        }


    });
}
window.modify = function (i) {
   if(sessionStorage.getItem("isgroup") == "0") {
        $("#width").attr("readonly", false);
        $("#high").attr("readonly", false);

    }else{
        $("#width").attr("readonly", true);
        $("#high").attr("readonly", true);
    }

    $("#myModal").find("span").empty();
    // $("#user_name").attr("disabled","disabled");
    $("#deviceid").attr("disabled", "disabled");
    $("#plcz").hide();
    $("#myModalLabel").text("修改");

    $("#update").click();
    i = i - 1;
    var jsonval = JSON.parse(json);
    console.log(jsonval.rows[i]); $("#deviceid").val(jsonval.rows[i].devicenumber);
    // $("#user_name").val(json[i].email);
    $("#co_idadd").val(jsonval.rows[i].devicenumber);
    $("#devicename").val(jsonval.rows[i].devicename);
    conamevlue = jsonval.rows[i].devicenumber;

    $("#company_nameadd").val(jsonval.rows[i].co_name);
    $("#company_id").val(jsonval.rows[i].co_id);


    $("#high").val(jsonval.rows[i].high);
    $("#width").val(jsonval.rows[i].width);

    $("#type").val(jsonval.rows[i].type)
    $("#type").attr("disabled", "disabled");
    $("#maxprogramnum").val(jsonval.rows[i].maxprogramnum);
    //alert(jsonval.rows[i].companyId);
    $("#maxPSDnum").val(jsonval.rows[i].maxprogramnum);

    $("#maxregionnum").val(jsonval.rows[i].maxprogramnum);




    $("#address").val(jsonval.rows[i].address);


    $("#longitude").val(jsonval.rows[i].longitude);
    $("#latitude").val(jsonval.rows[i].latitude);




    //$("#static").val(jsonval.rows[i].enter_state);
    //if(typeof(jsonval.rows[i].status)=="undefined"){
    //  $("#static").val("1");
    //}else{
    //  $("#static").val(jsonval.rows[i].status);
    //}
    // domain.jsonthis.userinfo=[json.rows[i].user_name];

};


Date.prototype.Format = function (fmt) {
    //author:wangweizhen
    var o = {
        "M+": this.getMonth() + 1,                 //月份   
        "d+": this.getDate(),                    //日
        "h+": this.getHours(),                   //小时   
        "m+": this.getMinutes(),                 //分   
        "s+": this.getSeconds(),                 //秒   
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度   
        "S": this.getMilliseconds()             //毫秒   
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}


// 设置
 // //选项卡
  // //关闭选项卡
 // if (typeof (parent.$("#tab_888").html()) != "undefined") {
//     parent.Addtabs.close("tab_888");
// }
// parent.addTabs({ id: '888', title: '设置', close: true, url: '?#/page/Device/devicesup' })



$(function(){


/**移动卡组**/
  var devicenumberval="";
     $("#moveGroup").click(function(){
        devicenumberval="";
        var ids = $("#table_list_1").jqGrid("getGridParam", "selarrrow");
        if(ids.length==0){
            swal("OMG!","请选择设备","error");
            setTimeout(function(){
            $("#addclose").click();
        },500);//延时显示卡号信息到文本框 
    }
        //由id获得对应数据行
        $(ids).each(function (index, id){
            var row = $("#table_list_1").jqGrid('getRowData', id);
             //由id获得对应数据行
             devicenumberval += row.devicenumber + ",";

        });
        if(devicenumberval.indexOf(",")!=-1){
        devicenumberval = devicenumberval.substring(0, devicenumberval.length - 1);
        }
       
        $("#deviceId").val(devicenumberval);

    
    });


    //保存移动的卡
    $("#addGroup").click(function () {
        if($("#company_id").val()==""){
            swal("OMG!", "请选择卡组", "error");
            return;
        }
          var msg = "确定移动这个设备吗？"; 
      if (confirm(msg)==true){   
           $.ajax({
               type: "post",
               url: domain.testUrl + "/Threeinjection/DeviceManagement/updateDeviceGroup",
               dataType: "text",
               timeout: 5000,//超时设置
               data: {
                   "sessionid": sessionStorage.getItem("sid"), "companyId": $("#company_id").val(),
                   "deviceNumber":  $("#deviceId").val()
               },

               success: function (data) {
                   console.log(data);
                   data = JSON.parse(data);
                   if (data != "") {
                       if (data.status == "error") {
                           swal("OMG!", "移除失败,卡号不在线！", "error");
                       } else {
                           swal("success!", "移除成功", "success");
                           $("#addclose").click();
                            pageval = 1;
                            cxlist();

                       }

                   } else {
                       swal("OMG!", "移除失败", "error");

                   }

               }
           });
           return true; 
      }else{
          return false; 
      }
     
   });


        
       
            
 });
   

//跳转到节目情况中
window.state=function(devicenumber){

    sessionStorage.setItem("deviceNumber",devicenumber); 
    $("#state").click();
   
    window.frames["iframescr"].window.cxlist();
  

    //加载iframe页面
    // setTimeout(function(){
    //     document.getElementById('iframescr').contentWindow.location.reload(true);
    //     },100);
   
    }


    





